<template>
  <div class="login-container">
    <nav-bar
      title="登录"
      :bgColor="themeColor"
      titleColor="#fff"
      supportWhiteBlack
    />
    <view>
      <view class="logo marginBottom-40 flexAIC">
        <image class="login-img" :showLoading="true" :src="logo" />
      </view>
      <view class="loginForm marginTop-40">
        <u--form
          labelWidth="auto"
          labelPosition="left"
          :model="loginForm"
          :rules="rules"
          ref="loginFormRef"
        >
          <u-form-item prop="phone" ref="phoneRef" borderBottom>
            <div class="flexAIC">
              <text class="iconfont icon-shouji marginRight-20"></text>
              <u--input
                border="none"
                v-model="loginForm.phone"
                placeholder="请输入手机号"
              ></u--input>
            </div>
          </u-form-item>
          <div class="marginTop-20" style="height: 20rpx"></div>
          <u-form-item prop="password" ref="passwordRef" borderBottom>
            <div class="flexAIC">
              <text class="iconfont icon-mima marginRight-20"></text>
              <u-input
                border="none"
                v-model="loginForm.password"
                placeholder="请输入密码"
              >
              </u-input>
            </div>
          </u-form-item>
          <div class="marginTop-60" style="height: 20rpx"></div>
          <u-form-item>
            <u-button
              :customStyle="{
                borderRadius: '18rpx',
              }"
              type="primary"
              text="登录"
              :disabled="!(!!loginForm.phone && !!loginForm.password)"
              @click="handleLogin"
            ></u-button>
          </u-form-item>
        </u--form>
      </view>
      <div class="loginForm flexAIC">
        <u-checkbox-group v-model="isConfirmContent" placement="column">
          <u-checkbox shape="circle" label="已阅读并同意" :name="true">
          </u-checkbox>
        </u-checkbox-group>
        <span class="text-28 text" @click="isShowAgreement = true"
          >《商户服务协议》</span
        >
      </div>
    </view>
    <u-popup
      :show="isShowAgreement"
      closeable
      mode="bottom"
      @close="isShowAgreement = false"
    >
      <view class="text-center agreement-content">商户服务协议</view>
      <view class="agreement-container">
        <text>
          首部及导言】
          欢迎您使用微盟商户助手APP！请您务必审慎阅读、充分理解各条款内容，如果您不同意本协议的任何内容，您应立即停止使用我们服务。当您使用我们提供的服务时，即视为您同意接受本协议的约束。
          一、适用范围 1.1
          本协议是关于您与微盟之间就使用微盟商户助手APP事宜订立的协议。“微盟”是指上海微盟企业发展有限公司及其相关服务可能存在的运营关联单位。“您”是指通过使用微盟商户助手APP进行订单处理、查询交易动态等操作的组织和个人。
          1.2
          本协议包括微盟公开发布的关于本服务的相关协议、服务声明、业务规则等内容。若您在本协议及具体规则内容生效后继续使用微盟服务的，表示您已经阅读、理解并接受修改后的协议和具体规则内容，也将遵循修改后的协议和具体规则使用微盟服务；同时就您在协议和具体规则修订前通过微盟进行的交易及其效力，视为您已同意并已按照本协议及有关规则进行了相应的授权和追认。若您不同意修改后的协议内容，请立即停止使用微盟服务。
        </text>
      </view>
    </u-popup>
    <u-action-sheet
      :actions="businessList"
      @select="handleSelectClick"
      @close="isShowBusinessList = false"
      cancelText="取消"
      safeAreaInsetBottom
      description="当前多个商户手机号和密码一样，请选择您要进入的商家助手"
      :show="isShowBusinessList"
    ></u-action-sheet>
  </div>
</template>

<script>
import { themeColor } from "@/const/theme/color";
import { getLoginBusinessList, login } from "@/service/api/sp-common/auth";
import { appGetStorage, appSetStorage } from "@/utils/storage";
import {
  PUB_BUSINESS_MA_LOGIN_PASSWORD,
  PUB_BUSINESS_MA_LOGIN_PHONE,
} from "@/const/application/auth";

export default {
  data() {
    return {
      logo: require("@/static/logo.png"),
      isConfirmContent: [false],
      isShowAgreement: false,
      isShowBusinessList: false,
      loginForm: {
        phone: "",
        password: "",
      },
      isShowPassword: false,
      rules: {
        phone: {
          type: "string",
          required: true,
          message: "请输入登录手机号",
          trigger: ["blur", "change"],
        },
        password: {
          type: "string",
          required: true,
          message: "请输入密码",
          trigger: ["blur", "change"],
        },
      },
      businessList: [],
    };
  },
  computed: {
    passwordEyeIcon({ isShowPassword }) {
      return isShowPassword ? "eye-off" : "eye-fill";
    },
    passwordType({ isShowPassword }) {
      return isShowPassword ? "text" : "password";
    },
    themeColor({ $theme }) {
      return $theme.themeColor.primary;
    },
  },
  watch: {},
  created() {
    this.loginForm.phone = appGetStorage(PUB_BUSINESS_MA_LOGIN_PHONE) || "";
    this.loginForm.password =
      appGetStorage(PUB_BUSINESS_MA_LOGIN_PASSWORD) || "";
  },
  methods: {
    handleLogin() {
      this.$refs.loginFormRef.validate().then(() => {
        appSetStorage(PUB_BUSINESS_MA_LOGIN_PHONE, this.loginForm.phone);
        appSetStorage(PUB_BUSINESS_MA_LOGIN_PASSWORD, this.loginForm.password);
        this.nextLogin();
      });
    },
    async nextLogin() {
      if (!this.isConfirmContent[0]) {
        uni.showModal({
          title: "提示",
          content: "请同意商户服务协议",
          confirmColor: themeColor.primary,
          success: (res) => {
            if (res.confirm) {
              this.isConfirmContent = null;
              this.$nextTick(() => {
                this.isConfirmContent = [true];
              });
            }
          },
        });
        return;
      }
      const businessList = await getLoginBusinessList(this.loginForm).catch(
        (err) => {
          uni.showToast({
            icon: "none",
            title: err.msg,
          });
        }
      );
      this.businessList = businessList?.map((v) => {
        v.name = v.businessName;
        return v;
      });
      if (this.businessList.length > 0) {
        if (this.businessList?.length === 1) {
          this.handleSelectClick(this.businessList[0]);
        } else {
          this.$nextTick(() => {
            this.isShowBusinessList = true;
          });
        }
      }
    },
    handleSelectClick(e) {
      const chooseBusinessInfo = e;
      login({
        phone: this.loginForm.phone,
        password: this.loginForm.password,
        businessId: chooseBusinessInfo.privateBusinessId,
        scope: "pubDomainBusinessApp",
        pubDomainBusinessId: chooseBusinessInfo.id,
      }).then((login_res) => {
        console.log("res", login_res);
        if (login_res) {
          uni.showToast({
            icon: "success",
            title: "登录成功",
          });
          this.$store.dispatch(
            "sp-common/auth/setUserInfoAction",
            chooseBusinessInfo
          );
          this.$store
            .dispatch("sp-common/auth/setTokenAction", login_res)
            .then(() => {
              setTimeout(() => {
                this.$Router.replaceAll({
                  path: "/pages/home/index",
                });
              }, 1900);
            });
        }
      });
    },
  },
};
</script>

<style scoped lang="scss">
.logo {
  margin-top: 20px;
  .login-img {
    margin: 0 auto;
    width: 143rpx;
    height: 143rpx;
  }
}
.loginForm {
  width: 630rpx;
  margin: 10px auto;
}
.text {
  color: $u-primary;
}
.agreement-container {
  padding: 20rpx;
  height: 50vh;
  overflow-y: scroll;
}
.agreement-content {
  padding: 30rpx 0;
}
</style>
